﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;

/* Copyright (c) 2014
 * author: Ricky Kratochwil
 * @ date: 2014-05-16
 * @ summary: This class manages all log calls
*/

namespace Engine
{
	class CLog
	{
		private static bool		s_bLog = false;
		private static string	s_strFilePath;


		/* Enable or disable log
		 *  @ requires:	
		 *      -/-
		 *  @ modifies:	
		 *      -/-
		 *  @ ensures:	
		 *     -/-
		 *  @ remarks:	
		 *     -/-
		 *  @ author / date:
		 *     - KR / 2014.05.16
		*/
		public static void EnableLog(bool bValue)
		{
			s_bLog = true;
		}


		/* Create new log
		 *  @ requires:	
		 *     - Vaild path
		 *  @ modifies:	
		 *     - Creates or overwrites log file
		 *  @ ensures:	
		 *     - File can be created
		 *  @ remarks:	
		 *     - Caller does not need to check if logging is enabled
		 *  @ author / date:
		 *     - KR / 2014.05.16
		*/
		public static void SetLog(string strAppName)
		{
			if(s_bLog)
			{
				FileStream   oLogFile    = null;
				StreamWriter oLogWriter  = null;

				s_strFilePath = Directory.GetCurrentDirectory() + '\\' + strAppName + ".log";

				try
				{
					//Create file
					oLogFile    = new FileStream(s_strFilePath, FileMode.Create, FileAccess.Write);
					oLogWriter  = new StreamWriter(oLogFile);

					oLogWriter.WriteLine("# " + DateTime.Now.ToString("s"));    //Set time of log creation
				}
				catch (Exception ex)
				{
					MessageBox.Show("Error creating log\n\n" + ex.Message);

					s_bLog = false;     //Prevent any follow up calls from executing
				}

				if(oLogWriter != null)
					oLogWriter.Close();
				if (oLogFile != null)
					oLogFile.Close();
			}
		}


		/* Places actual string into log
		 *  @ requires:	
		 *      -/-
		 *  @ modifies:	
		 *      - Writes into strContent into log file
		 *  @ ensures:	
		 *     - Log is enabled
		 *     - Open and close log after each action
		 *  @ remarks:	
		 *     - strContent does not need to include trailing line break
		 *  @ author / date:
		 *     - KR / 2014.05.16
		*/
		public static void Log(string strContent)
		{
			if (s_bLog)
			{
				FileStream		oLogFile	= null;
				StreamWriter	oLogWriter	= null;

				try
				{
					//open file
					oLogFile = new FileStream(s_strFilePath, FileMode.Append, FileAccess.Write);
					oLogWriter = new StreamWriter(oLogFile);

					oLogWriter.WriteLine(strContent);
				}
				catch (Exception)
				{
					//Once creation was successful, no errors should occure during writing
				}

				if (oLogWriter != null)
					oLogWriter.Close();
				if (oLogFile != null)
					oLogFile.Close();
			}
		}
	}
}
